﻿#region

using System;
using System.Web;
using Autofac;
using Autofac.Integration.Mvc;

#endregion

namespace HouseHoldBudget.Core.Infrastructure.DependencyManagement
{
    /// <summary>
    ///   An <see cref="IHttpModule" /> and <see cref="ILifetimeScopeProvider" /> implementation that creates a nested lifetime scope for each HTTP request.
    /// </summary>
    public class AutofacRequestLifetimeHttpModule : IHttpModule
    {
        #region Readonly & Static Fields

        /// <summary>
        ///   Tag used to identify registrations that are scoped to the HTTP request level.
        /// </summary>
        public static readonly object HttpRequestTag = "httpRequest";

        #endregion

        #region IHttpModule Members

        /// <summary>
        ///   Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context"> An <see cref="T:System.Web.HttpApplication" /> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
        public void Init(HttpApplication context)
        {
            context.EndRequest += ContextEndRequest;
        }

        /// <summary>
        ///   Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule" /> .
        /// </summary>
        public void Dispose()
        {
        }

        #endregion

        #region Class Properties

        private static ILifetimeScope LifetimeScope
        {
            get
            {
                return (ILifetimeScope) HttpContext.Current.Items[typeof (ILifetimeScope)];
            }
            set
            {
                HttpContext.Current.Items[typeof (ILifetimeScope)] = value;
            }
        }

        #endregion

        #region Class Methods

        /// <summary>
        ///   Gets a nested lifetime scope that services can be resolved from.
        /// </summary>
        /// <param name="container"> The parent container. </param>
        /// <param name="configurationAction"> Action on a <see cref="ContainerBuilder" /> that adds component registations visible only in nested lifetime scopes. </param>
        /// <returns> A new or existing nested lifetime scope. </returns>
        public static ILifetimeScope GetLifetimeScope(ILifetimeScope container, Action<ContainerBuilder> configurationAction)
        {
            //little hack here to get dependencies when HttpContext is not available
            if (HttpContext.Current != null)
            {
                return LifetimeScope ?? (LifetimeScope = InitializeLifetimeScope(configurationAction, container));
            }
            else
            {
                //throw new InvalidOperationException("HttpContextNotAvailable");
                return InitializeLifetimeScope(configurationAction, container);
            }
        }

        private static void ContextEndRequest(object sender, EventArgs e)
        {
            ILifetimeScope lifetimeScope = LifetimeScope;
            if (lifetimeScope != null)
                lifetimeScope.Dispose();
        }

        private static ILifetimeScope InitializeLifetimeScope(Action<ContainerBuilder> configurationAction, ILifetimeScope container)
        {
            return (configurationAction == null)
                       ? container.BeginLifetimeScope(HttpRequestTag)
                       : container.BeginLifetimeScope(HttpRequestTag, configurationAction);
        }

        #endregion
    }
}